package t1047

import (
	"fmt"
	"strings"
	"sync"
)

func removeDuplicates(S string) string {

	st := &MyStack{}

	for _, v := range S {
		val := string(v)
		if top, ok := st.Top(); ok && top == val {
			_, _ = st.Pop()
		} else {
			st.Push(val)
		}
	}

	return st.String()
}

type MyStack struct {
	item []string
	lock sync.Mutex
}

func (s *MyStack) Push(p string) {
	s.lock.Lock()
	defer s.lock.Unlock()
	s.item = append(s.item, p)
}

func (s *MyStack) Pop() (string, error) {
	s.lock.Lock()
	defer s.lock.Unlock()
	if s.Size() == 0 {
		return "", fmt.Errorf("stack is empty")
	}
	el := s.item[len(s.item)-1]
	s.item = s.item[:len(s.item)-1]
	return el, nil
}

func (s *MyStack) Top() (string, bool) {
	s.lock.Lock()
	defer s.lock.Unlock()
	if s.Size() == 0 {
		return "", false
	}
	el := s.item[len(s.item)-1]
	return el, true
}

func (s *MyStack) Size() int {
	return len(s.item)
}

func (s *MyStack) String() string {
	return strings.Join(s.item, "")
}
